/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ecmascript/tests/test_helper.h"

#include "common_interfaces/thread/thread_holder-inl.h"
#include "common_interfaces/thread/thread_holder.h"
#include "common_components/mutator/mutator.h"

using namespace common;

namespace common::test {
namespace {
    void SetCurrentThreadHolder(ThreadHolder* holder)
    {
        ThreadHolder::SetCurrent(holder);
    }
}

class ThreadHolderTest : public BaseTestWithScope<false> {
};

size_t callCount;
void CallBackVisitor(void *root)
{
    callCount++;
}

HWTEST_F_L0(ThreadHolderTest, ThreadHolderTest0) {
    ThreadHolder *curHolder = ThreadHolder::CreateAndRegisterNewThreadHolder(nullptr);
    ASSERT_TRUE(curHolder != nullptr);
    // Arrange
    SetCurrentThreadHolder(curHolder);

    curHolder->WaitSuspension();

    CommonRootVisitor visitor = nullptr;
    curHolder->VisitAllThreads(visitor);

    // Act
    ThreadHolder* result = ThreadHolder::GetCurrent();
    EXPECT_EQ(result, curHolder);
}

HWTEST_F_L0(ThreadHolderTest, ThreadHolderTest1) {
    ThreadHolder *curHolder = ThreadHolder::CreateAndRegisterNewThreadHolder(nullptr);
    ASSERT_TRUE(curHolder != nullptr);

    SetCurrentThreadHolder(curHolder);

    JSThread *jsThread = JSThread::Create(static_cast<EcmaVM *>(Mutator::GetMutator()->GetEcmaVMPtr()));
    ASSERT_TRUE(jsThread != nullptr);

    callCount = 0;
    curHolder->RegisterJSThread(jsThread);
    curHolder->VisitAllThreads(&CallBackVisitor);
    EXPECT_EQ(callCount, 1);
}

}  // namespace panda::test